package com.foreknow.jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;


public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out = resp.getWriter();
        //处理表单信息
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        //查询出来的信息
        String name1 = null;
        String password1 = null;

        //连接数据库处理信息
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/javaweb_test?charsetEncoding=UTF-8", "root", "root");
            PreparedStatement preparedStatement = connection.prepareStatement("select name,password FROM login_inf where name = ?");
            preparedStatement.setObject(1,name);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                 name1 = resultSet.getString("name");
                 password1 = resultSet.getString("password");
            }

            resultSet.close();
            preparedStatement.close();
            connection.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
        }


        if (name.equals(name1) && password.equals(password1)){

            out.println("true");

            HttpSession session = req.getSession();
            session.setAttribute("name",name);
            //跳转到list.jsp页面
            req.getRequestDispatcher("/list.jsp").forward(req,resp);


        }
        else {
            out.println("false");


        }



    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


    }
}
